package com.zlm.weather.controller;

import com.zlm.weather.pojo.WeatherResponse;
import com.zlm.weather.service.WeatherService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Author: 郑
 * @Date: Create in 2020-1-16.
 */
@Slf4j
@Controller
public class WeatherController {

    private static final long TIME_OUT = 1800L;

    @Autowired
    private WeatherService weatherService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping(value="/cityId/{cityId}")
    public String getByCityId(@PathVariable("cityId") String cityId){
        String result = stringRedisTemplate.opsForValue().get(cityId);
        if (StringUtils.isBlank(result)) {

            result = weatherService.getDataByCityId(cityId);
            stringRedisTemplate.opsForValue().set(cityId,result,TIME_OUT);
        }
        return result;
    }

    /**
     * 通过城市名查询天气
     * @param cityName
     * @param model
     * @return
     */
    @RequestMapping(value="/cityName/{cityName}")
    public String getByCityName(@PathVariable("cityName") String cityName, Model model){
        WeatherResponse result = weatherService.getDataByCityName(cityName);
        if (null == result) {
            log.error("{}天气查询失败",cityName);
        }
        model.addAttribute("report",result.getData());
        return "index::div1";
    }
}
